//
//  VideoChatViewController.m
//  UniversalApp
//
//  Created by 志刚杨 on 2018/2/11.
//  Copyright © 2018年 voidcat. All rights reserved.
//

#import "VideoChatViewController.h"
#import <TXLiteAVSDK_Professional/TXLivePlayer.h>
#import "RtmpManage.h"
#import "VideoChatUserView.h"
#import "UserInfoViewController.h"
#import "CallUserManger.h"
#import "CallUserViewController.h" //呼叫页面
#import "UserInfoLogic.h"
#import "VideoChatLogic.h"
#import "SDCycleScrollView.h"
#import "ShufflingModel.h"
#import "RootWebViewController.h"
#import <UIScrollView+MJExtension.h>
#import <UIScrollView+MJRefresh.h>
#define SDCycleHeight 140

@interface VideoChatViewController ()<RtmpManageDelegate,UserInfoLogicDelegate,VideoChatLogicDelegate>
@property(nonatomic, strong) VideoChatUserView *Video1;
@property(nonatomic, strong) VideoChatUserView *Video2;
@property(nonatomic, strong) VideoChatUserView *Video3;
@property(nonatomic, strong) CallUserManger *callManger;
@property(nonatomic, strong)  UserInfoLogic *logic;
@property(nonatomic, strong) VideoChatLogic *video_logic;
@property(nonatomic, strong) QMUIGhostButton *btnGetNew;
@property(nonatomic, strong) RtmpManage *rtmpManage;

@property(nonatomic, strong) NSMutableArray *listview;
@property(nonatomic, assign) int status;
@property(nonatomic,strong) SDCycleScrollView *cycleScrollView;
@property(nonatomic, strong) NSArray *CarouselModel;
@property(nonatomic, strong) UIScrollView *mainScrollView;
@property(nonatomic, strong) UIView *backgroundView;
@end
@implementation VideoChatViewController
{
    int _status;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = ASLocalizedString(@"视频聊");
    
    _mainScrollView = [[UIScrollView alloc] init];
    _mainScrollView.frame = self.view.bounds;

    //头部刷新
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    header.automaticallyChangeAlpha = YES;
    header.lastUpdatedTimeLabel.hidden = NO;
    _mainScrollView.mj_header = header;
    _mainScrollView.contentSize = CGSizeMake(0, SCREEN_HEIGHT);
    [self.view addSubview:_mainScrollView];
    
    _backgroundView = [[UIView alloc] init];
    [_mainScrollView addSubview:_backgroundView];
    
    [_mainScrollView addSubview:self.cycleScrollView];
    _logic = [UserInfoLogic new];
    _logic.delegagte = self;
    _Video1 = [[VideoChatUserView alloc] initWithFrame:CGRectMake(2, 2, 2, 2)];
    _Video2 = [[VideoChatUserView alloc] initWithFrame:CGRectMake(2, 2, 2, 2)];
    _Video3 = [[VideoChatUserView alloc] initWithFrame:CGRectMake(2, 2, 2, 2)];
    
    _callManger = [[CallUserManger alloc] init];
    @weakify(self)
    _Video1.UserVideoChatClick = ^(RandList *model) {
        [weak_self callWithUID:StringFromInt(model.id)];

    };
    
    _Video2.UserVideoChatClick = ^(RandList *model) {
        [weak_self callWithUID:StringFromInt(model.id)];
    };
    
    _Video1.backgroundColor = [UIColor whiteColor];
    _Video2.backgroundColor = [UIColor whiteColor];
    _Video3.backgroundColor = [UIColor whiteColor];

    _listview = [NSMutableArray array];
    [_listview addObject:_Video1];
    [_listview addObject:_Video2];
    
    [_backgroundView addSubview:_Video1];
    [_backgroundView addSubview:_Video2];
    
    _btnGetNew = [[QMUIGhostButton alloc] initWithGhostColor:MainColor];
    [_btnGetNew setTitle:ASLocalizedString(@"换一批")forState:UIControlStateNormal];
    [_btnGetNew addTarget:self action:@selector(getvideo) forControlEvents:UIControlEventTouchUpInside];
    _btnGetNew.hidden = YES;
    [self.view addSubview:_btnGetNew];
    [self setLayout];
    _rtmpManage = [RtmpManage new];
    _rtmpManage.delegate = self;
}


//测试
- (void)callWithUID:(NSString *)uid {
    
//    [[HUDHelper sharedInstance] syncLoading];
    [[HUDHelper sharedInstance] syncLoading:ASLocalizedString(@"请求中")inView:self.view];
    _logic.uid = uid;
    //防止请求用户失败一直不消失菊花
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(_status == 0)
        {
            [[HUDHelper sharedInstance] syncStopLoading];
        }
    });
    [_logic loadDataNoCache];
    
}

- (void)headerRereshing {
    [self getvideo];
}
#pragma mark - 数据加载完成回调
-(void)requestDataCompleted
{
    kWeakSelf(self)
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"video_call_api" A:@"video_call"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:_logic.uid forKey:@"id"];
    [CYNET POST:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // UI更新代码
            _status = 1;
            [[HUDHelper sharedInstance] syncStopLoading];
            //跳转到视频界面
            CallUserViewController *callView = [CallUserViewController new];
            callView.usermodel = _logic.model;
            callView.channel = [responseObject valueForKey:@"channel_id"];
            callView.iscall = YES;
            [weakself.navigationController pushViewController:callView animated:NO];
//            [self.navigationController pushViewController:callView animated:YES];
        });

    } failure:^(NSString *error) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [MBProgressHUD showTopTipMessage:error];
    } hasCache:NO];
    
}

-(void)getvideo
{
//    [[HUDHelper sharedInstance] syncLoading:ASLocalizedString(@"获取中")inView:self.view];
    [_rtmpManage getvideo];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setXR];
    
    _video_logic = [[VideoChatLogic alloc] init];
    _video_logic.delegagte = self;
    [_video_logic loadData];
    
    self.navigationController.navigationBar.hidden = NO;
//    [_rtmpManage update_live];
    [_rtmpManage getvideo];
    
}

- (void)setXR {
    //设置新轮播
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, KScreenWidth, SDCycleHeight) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
    cycleScrollView.currentPageDotColor = MainColor;
    cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    self.cycleScrollView = cycleScrollView;
    [_mainScrollView addSubview:self.cycleScrollView];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //释放推流
//    [self stopRtmp];
    
    //释放播放
    for (int i=0; i<_listview.count; i++) {
        VideoChatUserView *videoView = _listview[i];
        [videoView stopPlay];
    }
    [_rtmpManage removetime];
}

-(void)setLayout
{
    [@[_Video1,_Video2] mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(_preViewContainer.mas_bottom).offset(10);
//        make.width.equalTo(@(SCREEN_WIDTH/2));
        make.height.equalTo(@(SCREEN_WIDTH/2*4/3));
        make.top.equalTo(@145);
    }];
    
    [@[_Video1,_Video2] mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:3 leadSpacing:0 tailSpacing:0];
    
    [_btnGetNew mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_Video1.mas_bottom).offset(20);
        make.height.equalTo(@40);
        make.width.equalTo(@100);
        make.top.equalTo(_Video1.mas_bottom).offset(10);
        make.centerX.equalTo(self.view);
    }];
    
    [_mainScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
        make.width.equalTo(self.view);
//        make.right.equalTo(self.view);
    }];
    
    [_backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_mainScrollView);
        make.width.equalTo(_mainScrollView);
    }];
    
//    [_preViewContainer mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.width.equalTo(@(SCREEN_WIDTH/3));
//        make.height.equalTo(@(SCREEN_WIDTH/3*4/3));
//        make.right.equalTo(self.view);
//        make.top.equalTo(self.view);
//    }];
}



//rtmp数据更新时
-(void)updateRtmp:(updateLiveModel *)model
{
//    self.pushUrlStr = model.push_url;
//    NSLog(ASLocalizedString(@"推流地址%@"),model.push_url);
//    [self startRtmp];
}

-(void)updateRandVideo:(RandVideoModel *)model
{
    [_mainScrollView.mj_header setState:MJRefreshStateIdle];
    [[HUDHelper sharedInstance] syncStopLoading];
    
    _Video1.hidden = YES;
    _Video2.hidden = YES;
    
    for (int i=0; i<model.list.count && i<2; i++) {
        RandList *data = model.list[i];
        VideoChatUserView *videoView = _listview[i];
        videoView.hidden = NO;
        [videoView setRandVideo:data];
    }
}

//获取到轮播刷新数据
-(void)requestSlideDataCompletedWithData:(NSDictionary *)dic
{
    _CarouselModel = [NSArray modelArrayWithClass:[ShufflingModel class] json:dic];
    NSMutableArray *imagesURLStrings = [NSMutableArray array];
    
    if(KIOSBASE)
    {
        [imagesURLStrings addObject:[cyurl safeUrl:@"http://pic.qiantucdn.com/58pic/13/29/71/23U58PICasm_1024.jpg!/fw/780/watermark/url/L3dhdGVybWFyay12MS40LnBuZw==/align/center/crop/0x1024a0a0"]];
    }
    else
    {
        for(int i=0; i<_CarouselModel.count; i++)
        {
            ShufflingModel *item = _CarouselModel[i];
            [imagesURLStrings addObject:[cyurl safeUrl:item.image]];
        }
    }
    self.cycleScrollView.imageURLStringsGroup = imagesURLStrings;
}

#pragma mark -  scrollview回调
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    if(ValidArray(_CarouselModel))
    {
        ShufflingModel *model = _CarouselModel[index];
        model.url = model.url;
        RootWebViewController *web = [[RootWebViewController alloc] initWithUrl:model.url];
        web.isShowCloseBtn  = YES;
        
        RootNavigationController *loginNavi =[[RootNavigationController alloc] initWithRootViewController:web];
        [kRootViewController presentViewController:loginNavi animated:YES completion:nil];
        NSLog(ASLocalizedString(@"点击了第%ld个"),index);
    }

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
